package edu.sdjzu.exam.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import edu.sdjzu.exam.common.CommonResponse;
import edu.sdjzu.exam.dto.GradingDTO;
import edu.sdjzu.exam.service.exam.GradingService;
import edu.sdjzu.exam.mapper.exam.ExamMapper;
import edu.sdjzu.exam.domain.exam.Exam;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/grading-ui")
@RequiredArgsConstructor
@SaCheckLogin
@SaCheckRole("teacher")
public class GradingUIController {

    private final GradingService gradingService;
    private final ExamMapper examMapper;

    /**
     * 获取批改界面的完整数据（左侧学生列表 + 右侧题目详情）
     */
    @GetMapping("/exam/{examId}")
    public CommonResponse<GradingUIData> getGradingUIData(@PathVariable Long examId) {
        try {
            // 获取考试信息
            Exam exam = examMapper.selectExamById(examId);
            if (exam == null) {
                return CommonResponse.error("考试不存在");
            }
            
            List<GradingDTO.StudentGradingListDTO> students = gradingService.getStudentsForGrading(examId);
            
            GradingUIData data = new GradingUIData();
            data.setExamId(examId);
            data.setExamName(exam.getTitle());
            data.setStudents(students);
            
            return CommonResponse.success(data);
        } catch (Exception e) {
            log.error("获取批改界面数据失败", e);
            return CommonResponse.error("获取数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定学生的主观题详情（中间显示区域）
     */
    @GetMapping("/exam/{examId}/student/{studentId}/questions")
    public CommonResponse<List<GradingDTO.SubjectiveAnswerDTO>> getStudentQuestions(
            @PathVariable Long examId, 
            @PathVariable Long studentId) {
        try {
            log.info("开始获取学生 {} 在考试 {} 中的题目信息", studentId, examId);
            List<GradingDTO.SubjectiveAnswerDTO> questions = gradingService.getSubjectiveAnswers(examId, studentId);
            log.info("成功获取到 {} 道主观题", questions.size());
            return CommonResponse.success(questions);
        } catch (Exception e) {
            log.error("获取学生题目失败，examId: {}, studentId: {}", examId, studentId, e);
            return CommonResponse.error("获取题目失败：" + e.getMessage());
        }
    }

    /**
     * 自动保存单个题目的批改结果
     */
    @PostMapping("/auto-save")
    public CommonResponse<String> autoSaveGrading(@Valid @RequestBody GradingDTO gradingDTO) {
        try {
            gradingService.gradeSingleAnswer(gradingDTO);
            return CommonResponse.success("自动保存成功");
        } catch (Exception e) {
            log.error("自动保存失败", e);
            return CommonResponse.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 批改界面数据传输对象
     */
    public static class GradingUIData {
        private Long examId;
        private String examName;
        private List<GradingDTO.StudentGradingListDTO> students;

        // getters and setters
        public Long getExamId() { return examId; }
        public void setExamId(Long examId) { this.examId = examId; }
        public String getExamName() { return examName; }
        public void setExamName(String examName) { this.examName = examName; }
        public List<GradingDTO.StudentGradingListDTO> getStudents() { return students; }
        public void setStudents(List<GradingDTO.StudentGradingListDTO> students) { this.students = students; }
    }
}